package managers.conversationManager.services;

import java.io.IOException;
import java.io.ObjectInputStream;

import managers.conversationManager.ConversationManager;
import managers.conversationManager.GenericSocket;
import managers.conversationManager.OnlineConversation;
import managers.messengerManager.services.Service;
import spotGUI.floatingChatGUI.FloatingChat;
import spotGUI.floatingChatGUI.FloatingChatFrame;
import utils.StackTracePrinter;
import utils.UserData;

public class ConversationsListeningService extends Service {

	
	private ConversationManager convManager = ConversationManager.getSharedInstance();
	
	
	public ConversationsListeningService() {
		super("ConversationListening");
	}

	@Override
	public void run() {
		listenToConversationRequests();
	}
	
	private void listenToConversationRequests() {
		try {
			while (true) {
				GenericSocket s = convManager.getProtocol().acceptConversationRequest();

				try {
					ObjectInputStream ois = new ObjectInputStream(s.getInputStream());

					UserData user = (UserData) ois.readObject();
					manager.getDataManager().getUsers().put((Integer) user.getProperty("id"), user);
					FloatingChat chat = convManager.getChatManager().getChat((Integer)(user.getProperty("id")));
					if (chat != null) {
						if (chat.getConversation() instanceof OnlineConversation) {
							chat.setVisible(true);
						} else {
							chat.setConversation(new OnlineConversation((Integer) user.getProperty("id"), s));
						}
					} else {
						chat = new FloatingChatFrame();
						convManager.getChatManager().addChat((Integer) user.getProperty("id"), chat);
						
						chat.setReceiverName(user.getProperty("firstName")+" "+user.getProperty("surname"));
						
						chat.setConversation(new OnlineConversation((Integer) user.getProperty("id"), s));
					}

				} catch (IOException e) {
					StackTracePrinter.print(e);
				} catch (ClassNotFoundException e) {
					StackTracePrinter.print(e);
				}
			}
		} catch (Exception e) {
			//buttami fuori
		}
	}
	
}
